<template>
  <div v-loading="loading">
    <div class="attraction">
      <e-container>
        <div style="margin:10px 0 0 0">
          <div class="attract-title">旅游景区</div>
          <div class="attract-title2">ENJOY SCENIC VIEWS</div>
          <el-card>
            <form action="javascript:;" @submit="searchSubmit" class="form-search">
              <table class="jd-search">
                <tbody>
                  <tr>
                    <td>
                      <p class="search-radio">
                        <a href="javascript:;" @click="selectRadio('region', '')"
                          :class="{ active: !search.region }">全部</a>
                        <a href="javascript:;" v-for="r in mapattractionkind4" @click="selectRadio('region', r.id)"
                          :class="{ active: search.region == r.id }" v-text="r.name">
                        </a>
                        <el-input class="info-search-input" type="text" style="width: 250px" v-model="search.name"
                          placeholder="请输入关键词">
                        </el-input>
                        <el-button type="success" class="info-search-button" @click="searchSubmit"
                            icon="el-icon-search">
                        </el-button>
                      </p>
                    </td>
                  </tr>
                </tbody>
              </table>
            </form>

            <el-row :gutter="30" v-for="(items, rowIndex) in chunkedList" :key="rowIndex" class="jingdian">
              <el-col :span="12" v-for="(r, colIndex) in items" :key="r.id">
                <div class="custom-module" style="display: flex; align-items: center;"
                  @click.stop="handleNavigate(r.id)">
                  <img :src="getFirstImage(r.photo)" :alt="r.name"
                    style="width: 350px; height: 300px; margin-right: 10px;">
                  <div class="attraction-info">
                    <h2>{{ r.name }}</h2>
                    <p>地址：{{ r.address }}</p>
                    <p>开放时间：{{ r.startTime }}</p>
                    <el-button type="primary" @click="handleNavigate(r.id)" class="xiangqing-button">查看详情</el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
            <div style="margin-top: 10px;text-align: center">
              <el-pagination @current-change="loadList" :current-page="page" :page-size="15"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
              </el-pagination>
            </div>
          </el-card>
        </div>

      </e-container>
    </div>
  </div>
</template>
<style type="text/scss" scoped lang="scss">
.attraction{
  .form-search {
    margin-bottom: 20px;

    .jd-search {
      border-top: 0;
      border-left: 0;
      width: 100%;

      td {
        border-right: 0;
        border-bottom: 3px solid #DEDEDE;
        padding: 10px;
      }

      .search-radio {
        margin: -15px 0px 12px;
        a {
          display: inline-block;
          padding: 8px 10px;
          margin-right: 15px;
          border-radius: 5px;
        }

        a.active {
          background: #7fabbe;
          color: #ffffff;
        }
      }
    }

    .info-search-button {
      //margin-left: 40px;
      background-color: #7fabbe;
      border-color: #7fabbe;
    }

    .info-search-input {
      margin-left: 542px;
    }
  }

  .info-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
    display: block;
    color: #070707;
  }

  .info-header {
    //text-align: center;
    //background-color: #7fabbe;
    height: 50px;
    display: flex;
    //align-items: center;
    //justify-content: center;
    border-radius: 8px 8px 0 0;
  }
  .jingdian{
    height: 300px;
    margin-bottom: 27px;
    .custom-module {
      display: flex;
      height: 300px;
      align-items: center;
      border: 1px solid #ccc;
      //border-radius: 5px;
      //padding: 10px;
      margin-bottom: 15px;
      transition: all 0.3s ease;
      cursor: pointer;
      .xiangqing-button{
        background-color: #7fabbe;
        color: #f5f3f3;
        border-color:#7fabbe ;
        margin-left: 76px;
        margin-top: 15px;
        letter-spacing: 2px;
      }
      .xiangqing-button:hover{
        background-color: #81b3c7;
        color: #faf5f5;
        font-weight: bold;
        border-color:#bdd3dc ;
      }
      .attraction-info {
        flex: 1;
        padding: 11px;

        h2 {
          margin-top: 0;
          font-size: 20px;
          text-align: left;
        }

        p {
          margin: 5px 0;
          color: #555;
        }
      }
    }

    .custom-module:hover {
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
    }

  }
  .attract-title {
    text-align: center;
    font-size: 25px;
    width: 100%;
  }
  .attract-title2 {
    margin-bottom: 3%;
    color: #8c8c8c;
    text-align: center;
    font-size: 17px;
    width: 100%;
  }
}
</style>
<script>
import api from '@/api';
import { extend } from '@/utils/extend';
import objectDiff from 'objectdiff';


/**
 * 后台列表页面
 */
export default {
  data() {
    return {
      loading: false,
      list: [],
      search: {


        number: '',

        name: '',

        region: '',

        photo: '',

        startTime: '',

        food: '',

        address: '',

        price_start: '',
        price_end: '',

        clicks_start: '',
        clicks_end: '',

        introduction: '',

        addtime: '',

      },
      page: 1, // 当前页
      pagesize: 12, // 页大小
      totalCount: 0, // 总行数
      total: {},

      mapattractionkind4: [],
    }
  },
  watch: {
  },
  computed: {
    chunkedList() {
      const chunkSize = 2;
      const result = [];
      for (let i = 0; i < this.list.length; i += chunkSize) {
        const chunk = this.list.slice(i, i + chunkSize);
        result.push(chunk);
      }
      return result;
    }
  },
  methods: {
    getFirstImage(photo) {
      if (Array.isArray(photo)) {
        return photo[0] || ''; // 返回第一张图片，如果数组为空则返回空字符串
      }
      return photo; // 如果不是数组，直接返回photo
    },
    searchSubmit() {
      // 保存搜索条件到 Cookie
      this.saveSearchToCookie();
    
      // 重新加载列表，从第一页开始
      this.page = 1; // 设置为第一页
      this.loadList(this.page); // 调用加载方法
    },
    saveSearchToCookie() {
      // 将搜索条件保存到Cookie
      const searchData = JSON.stringify(this.search);
      document.cookie = `search=${searchData}; path=/`;
    },
    getSearchFromCookie() {
      // 从Cookie中获取搜索条件
      const cookies = document.cookie.split('; ').reduce((acc, cookie) => {
        const [key, value] = cookie.split('=');
        acc[key] = value;
        return acc;
      }, {});
      return cookies['search'] ? JSON.parse(cookies['search']) : {};
    },
    handleNavigate(id) {
      this.$router.push({ path: '/attractiondetail', query: { id: id } });
    },
    truncate(text) {
      if (!text) return '';
      return text.length > 500 ? text.slice(0, 500) + '...' : text;
    },
    loadList(page) {
      // 防止重新点加载列表
      if (this.loading) return;
      this.loading = true;
      this.page = page;
      // 从Cookie中获取筛选条件
      var filter = this.getSearchFromCookie();
      filter.page = page + "";
      filter.pagesize = this.pagesize + "";
      this.$post(api.attraction.weblist, filter).then(res => {
        this.loading = false;
        if (res.code == api.code.OK) {
          extend(this, res.data);
        } else {
          this.$message.error(res.msg);
        }
      }).catch(err => {
        this.loading = false;
        this.$message.error(err.message);
      });
    },
    selectRadio(target, name) {
      this.search[target] = name;
      this.searchSubmit(1);
    },
    
  },
  beforeRouteUpdate(to, form, next) {
    // 从Cookie中获取搜索条件
    var search = this.getSearchFromCookie();
    if (to.query.page) {
      this.page = Math.floor(to.query.page);
    }
    if (to.query.pagesize) {
      this.pagesize = Math.floor(to.query.pagesize);
    }

    // 移除不必要的查询参数
    const cleanQuery = {
      page: this.page,
      pagesize: this.pagesize
    };

    // 替换当前URL，只保留必要的查询参数
    this.$router.replace({
      path: this.$route.path,
      query: cleanQuery
    });
    this.loadList(1);
    next();
  },
  created() {
    // 从Cookie中获取搜索条件
    var search = this.getSearchFromCookie();
    if (this.$route.query.page) {
      this.page = Math.floor(this.$route.query.page);
    }
    if (this.$route.query.pagesize) {
      this.pagesize = Math.floor(this.$route.query.pagesize);
    }

    // 移除不必要的查询参数
    const cleanQuery = {
      page: this.page,
      pagesize: this.pagesize
    };

    // 替换当前URL，只保留必要的查询参数
    this.$router.replace({
      path: this.$route.path,
      query: cleanQuery
    });
    this.loadList(this.page);
  },
  mounted() {
  },
  destroyed() {
  }
}
</script>